package com.example.cinema.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.example.cinema.entity.Movie;
import com.example.cinema.entity.Result;
import com.example.cinema.entity.Schedule;
import com.example.cinema.mapper.MovieMapper;
import com.example.cinema.mapper.ScheduleMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yc138
 * @since 2024-08-26
 */
@RestController
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    MovieMapper movieMapper;

    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("queryMovies")
    public Page<Movie> queryMovies(@RequestBody Movie where,
                                   @RequestParam(defaultValue = "1") int current,
                                   @RequestParam(defaultValue = "8")int size){
        //不是搜索，正常显示换页
        if(where == null){
            // 有缓存
            if (current == 1 && redisTemplate.hasKey("queryMoviesCache")) {
                System.out.println("-----------queryMoviesCache------------");
                Object object = redisTemplate.opsForValue().get("queryMoviesCache");
                Page<Movie> data = (Page<Movie>) object;
                data = min(data);
                return data;
            }
            // 无缓存
            LambdaQueryWrapper<Movie> lqw = new LambdaQueryWrapper<>();
            //lqw.in(Movie::getStatus,1,2);
            lqw.orderByDesc(Movie::getId);
            Page<Movie> p = new PageDTO<>(current, size);
            Page<Movie> moviePage = movieMapper.selectPage(p, lqw);
            if(current==1) {
                // 保存到redis
                redisTemplate.opsForValue().set("queryMoviesCache", moviePage, 60 * 60 * 24, TimeUnit.SECONDS);
            }
            moviePage = min(moviePage);
            return moviePage;
        }else{
            LambdaQueryWrapper<Movie> lqw = new LambdaQueryWrapper<>();
            lqw.in(Movie::getStatus,1,2);
            lqw.orderByDesc(Movie::getId);
            if (where.getStatus() == 1){
                lqw.in(Movie::getStatus,1);
            }else if (where.getStatus() == 2){
                lqw.in(Movie::getStatus,2);
            }
            Page<Movie> p = new PageDTO<>(current, size);
            Page<Movie> moviePage = movieMapper.selectPage(p, lqw);
            moviePage = min(moviePage);
            if(current==1 && where.getStatus() == 0) {
                // 保存到redis
                redisTemplate.opsForValue().set("queryMoviesCache", moviePage, 60 * 60 * 24, TimeUnit.SECONDS);
            }else if(current == 1 && where.getStatus() == 2){                                                       //因为不能一直缓存，所以要考虑到时效
                redisTemplate.opsForValue().set("queryOnMovies",moviePage,60 * 60 * 24 , TimeUnit.SECONDS);
            }
            return moviePage;
        }
    }

    //查询修改最低价格
    public Page<Movie> min(Page<Movie> page){
        for (Movie movie : page.getRecords()) {
            //根据电影ID查询该电影所有场次的最低票价
            String minPrice = minPrice(movie.getId());
            movie.setPrice(minPrice);
        }
        return page;
    }

    @Autowired
    ScheduleMapper scheduleMapper;

    //根据id查询最低价格
    public String minPrice(int id){
        //查询排片表
        LambdaQueryWrapper<Schedule> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Schedule::getMid, id);
        List<Schedule> schedules = scheduleMapper.selectList(lqw);
        //有数据，上映
        if(schedules.size() > 1){
            Double min = schedules.get(0).getPrice();
            for (Schedule schedule : schedules) {
                if (schedule.getPrice() < min){
                    min = schedule.getPrice();
                }
            }
            return min.toString();
        }else if(schedules.size() == 1){
            return schedules.get(0).getPrice().toString();
        }else{
            return "待定";
        }
    }

    //查询最新放映的5部电影信息
    @RequestMapping("getFiveMovie")
    Result getFiveMovie(){
        List<Movie> fiveMovie = movieMapper.getFiveMovie();
        return new Result(1, "已查询成功", fiveMovie);
    }

    //关联查询出电影有关的所有信息
    @RequestMapping("findMovieMsgById")
    public Movie findMovieMsgById(int id){
        return movieMapper.findMovieStillById(id);
    }
    @RequestMapping("queryFile")
    public Page<Movie> queryFile(@RequestBody QyeryData qyeryData,
                                 @RequestParam(defaultValue = "1") int current,
                                 @RequestParam(defaultValue = "8")int size){
        System.out.println("qyeryData = " + qyeryData);


        LambdaQueryWrapper<Movie> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Movie::getId);

        if("搜索".equals(qyeryData.getMode())){
            if(qyeryData.getInput()!=null && qyeryData.getInput().isBlank()==false){
                lqw.or().like(Movie::getName, qyeryData.getInput());
                lqw.or().like(Movie::getActor, qyeryData.getInput());
                lqw.or().like(Movie::getArea, qyeryData.getInput());
                lqw.or().like(Movie::getDirector, qyeryData.getInput());
                lqw.or().like(Movie::getTime, qyeryData.getInput());
                lqw.or().like(Movie::getIntroduce, qyeryData.getInput());
                lqw.or().like(Movie::getType, qyeryData.getInput());
                lqw.or().like(Movie::getLength, qyeryData.getInput());
            }
            if(isNumeric(qyeryData.getInput())){
                System.out.println(Integer.parseInt(qyeryData.getInput()));
                lqw.or().eq(Movie::getId, Integer.parseInt(qyeryData.getInput()));
            }
            if("上映中".equals(qyeryData.getInput())){
                lqw.or().eq(Movie::getStatus, 2);
            }
            if("即将上映".equals(qyeryData.getInput())){
                lqw.or().eq(Movie::getStatus, 1);
            }
            if("下映".equals(qyeryData.getInput())){
                lqw.or().eq(Movie::getStatus, 0);
            }
        }else {
            if(qyeryData.getTime()!=null &&qyeryData.getTime().isBlank()==false && "全部".equals(qyeryData.getTime())==false){
                lqw.like(Movie::getTime, Integer.parseInt(qyeryData.getTime().substring(0,4))+1);
            }
            if(qyeryData.getType()!=null && qyeryData.getType().isBlank()==false && "全部".equals(qyeryData.getType())==false){
                lqw.like(Movie::getType, qyeryData.getType());
            }
            if(qyeryData.getArea()!=null && qyeryData.getArea().isBlank()==false && "全部".equals(qyeryData.getArea())==false){
                lqw.like(Movie::getArea, qyeryData.getArea());
            }
            if(qyeryData.getStatus()!=null && qyeryData.getStatus().isBlank()==false && "全部".equals(qyeryData.getStatus())==false){
                if("上映中".equals(qyeryData.getStatus())){
                    lqw.eq(Movie::getStatus, 2);
                }
                if("即将上映".equals(qyeryData.getStatus())){
                    lqw.eq(Movie::getStatus, 1);
                }
                if("下映".equals(qyeryData.getStatus())){
                    lqw.eq(Movie::getStatus, 0);
                }

            }
        }
        Page<Movie> p = new PageDTO<>(current, size);
        Page<Movie> moviePage = movieMapper.selectPage(p, lqw);

        return moviePage;
    }

    public boolean isNumeric(String strNum) {
        if (strNum == null) {
            return false;
        }
        try {
            Integer.parseInt(strNum);
            return true;
        } catch (NumberFormatException e1) {
            return false;
        }
    }

    @RequestMapping("updateStatus")
    Result updateStatus(@RequestParam int id,
                        @RequestParam int status){
        Movie m = new Movie();
        m.setStatus(status);
        LambdaQueryWrapper<Movie> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Movie::getId,id);
        int update = movieMapper.update(m, lqw);
        if(update ==1){
            return new Result(1, "成功", null);
        }else {
            return new Result(0, "失败", null);
        }

    }


    @Value("${spring.datasource.password}")
    String pwd;
    @RequestMapping("aaaa")
    public Object aaa(){
        return pwd;
    }


}

@Data
@NoArgsConstructor
@AllArgsConstructor
class QyeryData{
    private String mode;
    private  String input;
    private String area;
    private String type;
    private String time;
    private String status;

}

